import { expandField } from '@src/component/form/util';
import { parseDateTime } from 'pub-bbx-utils';
import { fmt_form_date } from '@src/filter/form.js';

/** 将form对象转成后端可接收的数据，用于提交表单 */
export function packToProjectType(fields, form) {
  let params = {
    id: form.id,
    projectName: '', // 项目名称
    planStartTime: '', // 计划开始时间
    planEndTime: '', // 计划结束时间
    customerId: '',
    linkmanId: '',
    addressId: '',
    productId: [],
    synergies: [], // 协同人
    manager: {}, // 负责人
    projectAttribute: {}, // 自定义属性
  };

  expandField(fields).forEach(field => {
    let { fieldName, isSystem, formType } = field;
    let value = form[fieldName];

    // 系统字段特殊处理
    if (!!isSystem) {
      params.projectName = form['projectName'];

      if (fieldName === 'customer') {
        params.customerId = (value || []).map(item => item.id).join();
      }

      if (fieldName === 'linkman') {
        params.linkmanId = (value || []).map(item => item.id).join();
      }

      if (fieldName === 'address' && formType === 'customerAddress') {
        params.addressId = (value || []).map(item => item.id).join();
      }

      if (fieldName === 'product') {
        params.productId = (value || []).map(item => item.id);
      }

      if (fieldName === 'synergies') {
        params.synergies = (value || []).map(item => {
          return {
            userId: item?.userId,
            displayName: item?.displayName,
            staffId: item?.staffId,
          };
        });
      }

      if (fieldName === 'managerPerson') {
        params.manager = {
          userId: value?.userId,
          displayName: value?.displayName,
          staffId: value?.staffId,
        };
      }

      params['planStartTime'] = form['planStartTime'];
      params['planEndTime'] = form['planEndTime']
    } else {
      params.projectAttribute[fieldName] = value;
    }
  });

  return params;
}

/** 将对象转成form表单，用于初始化表单 */
export function packToProjectTypeForm(data) {
  let { address, customer = {}, linkman = {}, product, planStartTime, planEndTime } = data || {};
  let { id, name } = customer || {};

  let attribute = {
    ...data.attribute,
  };

  let allProduct = (product || []).map(item => {
    return {
      label: item.name,
      value: item.id,
      id: item.id,
    };
  });

  let form = {
    address: [
      {
        ...address,
      },
    ],
    customer: [
      {
        value: id,
        label: name,
        id: id,
      },
    ],
    linkman: [
      {
        ...linkman,
      },
    ],
    product: allProduct,
    planStartTime: fmt_form_date(planStartTime),
    planEndTime: fmt_form_date(planEndTime),
  };
  return Object.assign(data, attribute, form);
}
